//
//  TravelViewController.m
//  A段项目
//
//  Created by 刘言松 on 15/10/8.
//  Copyright (c) 2015年 刘言松. All rights reserved.
//

#import "TravelViewController.h"
#import "UIImageView+WebCache.h"
#import "TravelCollectionViewCell.h"
#import "TravelCollectionReusableView.h"
#import "SDCycleScrollView.h"
#import "TravelModel.h"
#import "MJRefresh.h"
#import "TravelDetailViewController.h"
#import "WebContentViewController.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <AFNetworking.h>
#import "AlertNetWork.h"


#define CELLFIGHT (HEIGHT*0.3)

@interface TravelViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,MyclickDele>

@end

@implementation TravelViewController



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
  
    
    self.dataArray = [NSMutableArray array];
    self.cacheArray = [NSMutableArray array];
    [self setCollectionView];
    

}


- (void)setCollectionView{
    
    UICollectionViewFlowLayout
    *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT * 0.3);
    flowLayout.minimumLineSpacing = 0;
    
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, HEIGHT * 0.05);
    
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.myCollectionView = [[BaseCollectionView alloc] initWithFrame: CGRectMake(0, 0, WIDTH, HEIGHT - 113) collectionViewLayout:flowLayout];
    

    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    
    [self.view addSubview:self.myCollectionView];
    
    [self.myCollectionView registerClass:[TravelCollectionViewCell  class] forCellWithReuseIdentifier:@"reuseIdentifier"];
    
    [self.myCollectionView registerClass:[TravelCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"travelHeader"];
    
    [self addHeaderRefresh];
    [self addFooterRefresh];
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TravelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    TravelModel *travel = [self.dataArray objectAtIndex:indexPath.row];
    
    cell.index = indexPath.row;
    cell.dele = self;
    
    [cell setData:travel];
    
    return cell;
}

-(void)clickmyItem:(NSInteger)index
{
    TravelDetailViewController *detail = [[TravelDetailViewController alloc]init];
    
    
    detail.hidesBottomBarWhenPushed = YES;
    NSString *ID = [[self.dataArray objectAtIndex:index]travel_id];
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1&sign=dea21f7ed5e413c82c05a351135ed1e8",ID];
    detail.UrlStr = urlStr;
    [self.navigationController pushViewController:detail animated:YES];
}

 

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    [self setMyCellOffset];

}


-(void)setMyCellOffset
{
    
    float cuHeight =  (HEIGHT - 113);
    
    int first = self.myCollectionView.contentOffset.y / CELLFIGHT;
    int myLast;
    
    
    float last = (self.myCollectionView.contentOffset.y + cuHeight)/CELLFIGHT;
    
    if ((last - (int)last ) > 0) {
        
        myLast = (int)last + 1;
    }
    
    
    for (int i = first; i < myLast; i ++) {
        
        NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
        
        
        float f =   i*CELLFIGHT - self.myCollectionView.contentOffset.y;
        
        float bi = ( f / cuHeight);
        
        TravelCollectionViewCell *cell =(TravelCollectionViewCell *) [self.myCollectionView  cellForItemAtIndexPath:path];
        
                 
        cell.myImageView.y =  - ( ( 1 - bi) *HEIGHT  * 0.3 *0.28);
               
        
        
        
    }
    
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader){
        
        TravelCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"travelHeader" forIndexPath:indexPath];
        
        headerView.titleLabel.text = @"精彩游记和专题";
        reusableview = headerView;
    }
    
    return reusableview;
}


- (void)addHeaderRefresh
{
    
    self.myCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
         [self getData];
        
    }];
    
    
    [self.myCollectionView.header beginRefreshing];
}

- (void)addFooterRefresh
{
    
    self.myCollectionView.footer  = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        NSString *next_Url = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index?next_start=%@",self.next_start];
        [self getNextData:next_Url];
        
    }];
    
  
}

- (void)filing_write:(NSArray *)array FilePath:(NSString *)filePath{
    NSArray *tmpArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [tmpArray lastObject];
    NSString *breadFilePath = [documentPath stringByAppendingString:filePath];
    
    BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:breadFilePath];
    if (result == NO) {
        NSLog(@"失败");
    }
}

- (NSArray *)filing_read:(NSString *)filePath{
    NSArray *tmpArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [tmpArray lastObject];
    NSString *breadFilePath = [documentPath stringByAppendingString:filePath];
    NSArray *array = [NSArray array];
    array = [NSKeyedUnarchiver unarchiveObjectWithFile:breadFilePath];
    return array;
}

- (void)getNextData:(NSString *)UrlStr{
    
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager.requestSerializer setValue:@"BreadTrip/6.1.1/zh (iPhone7,1; iPhone OS8.1.3; zh-Hans zh_CN) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];

    [manager GET:UrlStr parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
       
        self.next_start = [responseObject objectForKey:@"next_start"];
        NSArray *Array = [responseObject objectForKey:@"elements"];
        
        for (NSDictionary *tmpDic in Array) {
             if ([[NSString stringWithFormat:@"%@",[tmpDic objectForKey:@"type"]]  isEqual: @"4"]) {
            NSDictionary *dic = [[tmpDic objectForKey:@"data"]objectAtIndex:0];
            
            TravelModel *travel = [[TravelModel alloc]init];
            
            [travel setValuesForKeysWithDictionary:dic];
            travel.travel_id = [dic objectForKey:@"id"];
            travel.user_avatar = [[dic objectForKey:@"user"]objectForKey:@"cover"];
            travel.user_name = [[dic objectForKey:@"user"]objectForKey:@"name"];
            [self.dataArray addObject:travel];
           
             }
        }
        [self filing_write:self.dataArray FilePath:@"bread"];
        [self.myCollectionView reloadData];
        [self.myCollectionView.header endRefreshing];
        [self.myCollectionView.footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        [self.myCollectionView.header endRefreshing];
        [self.myCollectionView.footer endRefreshing];
        
    }];
}

- (void)getData{
    
    NSString *UrlStr = @"http://api.breadtrip.com/v5/index";
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager.requestSerializer setValue:@"BreadTrip/6.1.1/zh (iPhone7,1; iPhone OS8.1.3; zh-Hans zh_CN) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    
    
    [manager GET:UrlStr parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        [self.dataArray removeAllObjects];
        self.next_start = [responseObject objectForKey:@"next_start"];
        NSArray *Array = [responseObject objectForKey:@"elements"];
        
        for (int i = 7; i < Array.count; i++) {
            NSDictionary *dic = [[[Array objectAtIndex:i]objectForKey:@"data"]objectAtIndex:0];
            if ([[NSString stringWithFormat:@"%@",[[Array objectAtIndex:i]objectForKey:@"type"]]  isEqual: @"4"]) {
                TravelModel *travel = [[TravelModel alloc]init];
                
                [travel setValuesForKeysWithDictionary:dic];
                travel.travel_id = [dic objectForKey:@"id"];
                
                travel.user_avatar = [[dic objectForKey:@"user"]objectForKey:@"cover"];
                travel.user_name = [[dic objectForKey:@"user"]objectForKey:@"name"];
                [self.dataArray addObject:travel];
               
            }
        }
        NSArray *cacheArray = [NSArray arrayWithArray:self.dataArray];
        [self filing_write:cacheArray FilePath:@"bread"];
        
        [self.myCollectionView reloadData];
        [self.myCollectionView.header endRefreshing];
        [self.myCollectionView.footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [self.myCollectionView.header endRefreshing];
        [self.myCollectionView.footer endRefreshing];

        
        self.dataArray = [NSMutableArray arrayWithArray:[self filing_read:@"bread"]];
        
        
        [self.myCollectionView reloadData];
    }];
}

@end
